<template>
  <PlatformDropdown @platformChange="platformChange">
    <div class="function-container">
      <div class="function-left-tree">
        <div class="function-left-container">
          <el-tree
            ref="functionLeftTree"
            :data="treeDatas"
            :props="defaultProps"
            node-key="treeIndex"
            default-expand-all
            :expand-on-click-node="false"
            :highlight-current="true"
            @node-click="clickdNode"
          />
        </div>
      </div>
      <div class="function-right-manager">
        <div class="function-table-btns">
          <el-button type="primary" size="small" @click="newFunction">新增</el-button>
        </div>
        <div ref="table-view" class="function-table-view">
          <el-table v-if="showTable" v-loading="loadingTable" :height="tableHeight" border style="width: 100%" :data="functionList">
            <el-table-column type="expand">
              <template #default="props">
                <el-table :data="props.row.functionApis" style="width: 100%">
                  <el-table-column prop="apiDes" label="描述" width="180" />
                  <el-table-column prop="apiUrl" label="url" width="180" />
                  <el-table-column prop="apiKey" label="key" />
                </el-table>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="功能名称" />
            <el-table-column prop="menuName" label="菜单名称" />
            <el-table-column fixed="right" label="Operations" width="120">
              <template #default="scope">
                <el-popconfirm
                  confirm-button-text="确认"
                  cancel-button-text="不用了"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除吗？"
                  @onConfirm="deletedFunction(scope.row.id)"
                >
                  <el-button slot="reference" type="text" size="small">delete</el-button>
                </el-popconfirm>
                <el-button type="text" size="small" @click.prevent="editedFunction(scope.row)">edited</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="confirm-view">
        <el-dialog :visible="dialogFormVisible" :title="isUpdate? '编辑角色信息' : '新增角色'" :show-close="false">
          <el-form ref="dialogForm" :model="dialogForm" label-width="60px">
            <el-form-item label="名称">
              <el-input v-model="dialogForm.name" placeholder="输入名称" />
            </el-form-item>
            <el-form-item label="api">
              <div class="api-tree-container">
                <el-tree
                  ref="apiTree"
                  :data="apiTreeDatas"
                  show-checkbox
                  default-expand-all
                  node-key="key"
                  highlight-current
                  :props="apiProps"
                />
              </div>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="cancelForm">取消</el-button>
              <el-button type="primary" @click="confirmForm">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </PlatformDropdown>
</template>
<script>
import { tree } from '@/api/menu.js'
import { listByMenuId, newsFunction, edited, deleted } from '@/api/function.js'
import table from '@/mixin/table-view.js'
import { tree as apiTree } from '@/api/api.js'
import PlatformDropdown from '@/components/PlatformDropdown/index.vue'

export default {
  name: `function-manager`,
  components: { PlatformDropdown },
  mixins: [table],
  data() {
    return {
      functionList: [],
      menuData: {},
      loadingTable: false,
      treeDatas: [],
      defaultProps: {
        children: 'childrens',
        label: 'title'
      },
      isUpdate: true,
      dialogFormVisible: false,
      dialogForm: {},
      apiTreeDatas: [],
      apiProps: {
        children: 'childrens',
        label: 'des'
      },
      curMenuId: null,
      platformCode: null
    }
  },
  async mounted() {
    await this.initApiTree()
  },
  methods: {
    async refreshData() {
      this.dialogForm = {}
      await this.refreshTree()
      await this.refreshList()
    },
    platformChange(platformCode) {
      this.platformCode = platformCode
      this.refreshData()
    },
    initApiTree() {
      this.apiTreeDatas = []
      return apiTree().then(rsp => {
        if (rsp && rsp.code === 200) {
          this.apiTreeDatas = rsp.data || []
        } else {
          this.$message.error('api初始化失败')
        }
      }).catch(e => {
        this.$message.error('api初始化失败')
        console.error('api初始化失败', e)
      })
    },
    refreshTree() {
      this.treeDatas = []
      return tree({ platformCode: this.platformCode }).then(rsp => {
        if (rsp && rsp.code === 200) {
          this.treeDatas = rsp.data || []
          const node = this.treeDatas[0]
          if (node) {
            this.$nextTick(() => {
              this.$refs['functionLeftTree'].setCurrentKey(node.treeIndex)
              this.curMenuId = node.id
            })
          }
        } else {
          this.$message.error('刷新失败')
        }
      }).catch(e => {
        this.$message.error('刷新失败')
        console.error('刷新失败', e)
      })
    },
    clickdNode(data, node, nodeEl) {
      const nodeData = data || node.data
      this.menuData = nodeData
      this.curMenuId = nodeData.id
      this.refreshList()
    },
    refreshList() {
      this.functionList = []
      return listByMenuId({ menuId: this.curMenuId, platformCode: this.platformCode }).then(rsp => {
        if (rsp && rsp.code === 200) {
          this.functionList = rsp.data || []
          this.loadingTable = false
        } else {
          this.loadingTable = false
          this.$message.error('刷新失败')
        }
      }).catch(e => {
        this.loadingTable = false
        this.$message.error('刷新失败')
        console.error('刷新失败', e)
      })
    },
    newFunction() {
      this.isUpdate = false
      this.dialogFormVisible = true
      this.dialogForm = { menuId: this.curMenuId, platformCode: this.platformCode }
      this.$nextTick(() => {
        this.$refs.apiTree.setCheckedKeys([])
      })
    },
    deletedFunction(id) {
      deleted({ id }).then(rsp => {
        console.log(rsp)
        this.refreshList()
      })
    },
    editedFunction(functionData) {
      this.isUpdate = true
      this.dialogFormVisible = true
      this.dialogForm = functionData
      this.$nextTick(() => {
        this.$refs.apiTree.setCheckedKeys(functionData.functionApis.map(item => item.apiKey))
      })
    },
    confirmForm() {
      const apinodes = this.$refs.apiTree.getCheckedNodes() || []
      this.dialogForm.functionApiNewRequs = apinodes.filter(item => !item.childrens).map(item => { return { apiKey: item.key, apiUrl: item.path, apiDes: item.des } })
      if (this.isUpdate) {
        edited(this.dialogForm).then(rsp => {
          console.log(rsp)
          if (rsp.data) {
            this.refreshList()
            this.dialogFormVisible = false
          } else {
            this.$message.error('修改失败')
          }
        }).catch(e => {
          this.dialogFormVisible = false
          this.$message.error('修改失败')
          console.error('修改失败', e)
        })
      } else {
        newsFunction(this.dialogForm).then(rsp => {
          if (rsp.data) {
            this.refreshList()
            this.dialogFormVisible = false
          } else {
            this.$message.error('新增失败')
          }
        }).catch(e => {
          this.dialogFormVisible = false
          this.$message.error('新增失败')
          console.error('新增失败', e)
        })
      }
    },
    cancelForm() {
      this.dialogFormVisible = false
    }
  }
}
</script>

<style lang="scss">
.function-container{
  display: flex;
  width: 100%;
  height: 100%;
  flex-wrap: nowrap;
    .function-left-tree{
      padding: 10px 0 0 20px;
      width: 300px;
      height: 100%;
      overflow: hidden;
      position: relative;
      .function-left-container{
        height: 100%;
        width: 100%;
        overflow: scroll;
        position: relative;
        &::-webkit-scrollbar {
          width: 7px;
          height: 8px;
        }
        &::-webkit-scrollbar-thumb {
          background-color: rgba(144,147,153,.3);
          border-radius: 2px;
          box-shadow: inset 0 0 6px rgb(0 0 0 / 20%);
        }
        &::-webkit-scrollbar-track {
          background-color: rgba(0,0,0,.05);
        }
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          padding-right: 8px;
          .tree-node-tools {
            margin: 0 3px;
          }
        }
      }
    }
    .function-right-manager{
      padding: 10px 20px 10px;
      width: 100%;
      display: flex;
      overflow: hidden;
      flex-direction: column;
      .function-table-btns{
        padding: 10px 1px;
        flex-grow: 0;
      }
      .function-table-view{
        height: 100%;
        overflow: hidden;
      }
    }
  .confirm-view{
    .el-dialog__wrapper .el-dialog {
      width: 520px;
      padding-right: 50px;
      .el-dialog__body{
        .el-form{
          label{
            width: 60px;
          }
          .el-form-item__content{
            width: 400px;
            .el-select.el-select--medium{
              width: 100%;
            }
            .el-cascader.el-cascader--medium{
              width: 100%;
            }
          }
        }
      }
      .el-dialog__footer{
        height: 60px;
        .dialog-footer{
          transform: translateX(-50%);
          left: 50%;
          position: absolute;
        }
      }
    }
    .api-tree-container{
      height: 300px;
      overflow: scroll;
      &::-webkit-scrollbar {
        width: 7px;
        height: 8px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: rgba(144,147,153,.3);
        border-radius: 2px;
        box-shadow: inset 0 0 6px rgb(0 0 0 / 20%);
      }
      &::-webkit-scrollbar-track {
        background-color: rgba(0,0,0,.05);
      }
    }
  }
}
</style>
